package com.example.warehousems.controller;

import com.example.warehousems.component.BaseResponse;
import com.example.warehousems.component.UserInfo;
import com.example.warehousems.dao.model.Activity;
import com.example.warehousems.service.ActivityService;
import com.example.warehousems.service.MessageService;
import com.example.warehousems.vo.ActivityVO;
import com.example.warehousems.vo.MessageIdVO;
import com.example.warehousems.vo.MessageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/activity")
@Slf4j
public class ActivityController {
    @Autowired
    private ActivityService activityService;

    @GetMapping("/")
    BaseResponse getAll() {
        var userId = Integer.valueOf(UserInfo.get("id"));
        log.info("Get all activities for user {}", userId);
        if (!UserInfo.get("role").equals("admin"))
            return BaseResponse.success(activityService.getAll(userId));
        return BaseResponse.success(activityService.getAll());
    }

    @GetMapping("/page/{pageNum}/{pageSize}")
    BaseResponse getAllPage(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        var userId = Integer.valueOf(UserInfo.get("id"));
        log.info("Get all activities for user {}", userId);

        Pageable pageable = PageRequest.of(pageNum, pageSize);
        Page<Activity> activityPage;

        if (!UserInfo.get("role").equals("admin")) {
            activityPage = activityService.getAllByUserId(userId, pageable);
        } else {
            activityPage = activityService.getAll(pageable);
        }

        return BaseResponse.success(activityPage.getContent());
    }

    @PostMapping("/")
    BaseResponse addActivity(@RequestBody ActivityVO activityVO) {
        var userId = Integer.valueOf(UserInfo.get("id"));
        activityService.addActivity(userId, activityVO.getTitle(), activityVO.getDescription());
        return BaseResponse.success("Activity sent");
    }

    @PutMapping("/read")
    BaseResponse markAllAsRead(@RequestBody MessageIdVO ids) {
        log.info(ids.toString());
        var userId = Integer.valueOf(UserInfo.get("id"));
        log.info("Mark all messages as read for user {}", userId);
        activityService.markAllAsRead(userId, ids.getIds());
        return BaseResponse.success("ok");
    }
}
